package adminorg;


import java.util.Arrays;

import com.oros.db.AEForeignKeyException;
import com.vaadin.data.Item;
//import com.vaadin.data.util.filter.Compare.Equal;
//import com.vaadin.data.util.sqlcontainer.SQLContainer;
import com.vaadin.data.validator.EmailValidator;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.Button;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;
//import com.vaadin.ui.TabSheet.SelectedTabChangeEvent;
import com.vaadin.ui.Window.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Table;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Runo;
import com.vaadin.ui.Field;
import com.vaadin.ui.Component;
import com.vaadin.data.Container;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;

import adminorg.DatabaseHelper;
import adminorg.confWindow;
//import adminorg.db.*;



public class CompanyForm extends Accordion{


	private static final long serialVersionUID = 7585826489324450967L;
	private Accordion compaccordion = null;
	private VerticalLayout CmainLayout = null;
	private VerticalLayout CDetailLayout = null;
	private HorizontalLayout CDhLayout2 = null;
	private HorizontalLayout ChLayout2 = null;
	private Panel Cpanel = null;
	private Panel CgridPanel = null;
	private Panel CDpanel = null;
	private Panel CDgridPanel = null;
	private VerticalLayout CvLayout2 = null;
	private HorizontalLayout ChLayout3 = null;
	private VerticalLayout CDvLayout2 = null;
	private HorizontalLayout CDhLayout3 = null;
	private Button bCancel = null;
	private Button bAply = null;
	private Button bDCancel = null;
	private Button bDAply = null;
	private Table CompGrid = null;
	private Table CompAccGrid = null;
	private MenuBar CmenuBar = null;
	private MenuBar CDmenuBar = null;
	private Object MainId = null;
	private Form CompForm = null;
	private Form CompAccForm = null;
	private MenuBar.MenuItem mAdd = null;
	private MenuBar.MenuItem mEdit = null;
	private MenuBar.MenuItem mDel = null;
	private MenuBar.MenuItem mRefresh = null;
	private MenuBar.MenuItem mdAdd = null;
	private MenuBar.MenuItem mdEdit = null;
	private MenuBar.MenuItem mdDel = null;
	private DatabaseHelper dbHelp = null;
	private Object editComAccId = null;
	
	
	private static final Object[] DCOLS = new Object[]{"email","nik","name","isadmin","isstatadmin","isstatuser","ispanel","isprocessadmin","isprocessuser","isfinuser","istrainingadmin"};
	private static final Object[] DBCOLS = new Object[]{"isadmin","isstatadmin","isstatuser","ispanel","isprocessadmin","isprocessuser","isfinuser","istrainingadmin"};
	private static final String[] DCAPT = new String[]{"Account","Nick","Name","OrgChartAdmin","AdminSt","UserSt","PanelAdmin","BPAdmin","BPUser","FinModule","CourseAdmin"};  
	
	private Command menuCommand = new Command() {
		private static final long serialVersionUID = 2164852947325709550L;
        private void enableCPanel()
        {
        	Cpanel.setVisible(true);
        	mEdit.setEnabled(false);
        	mDel.setEnabled(false);
        }
        private void disableCPanel()
        {
        	Cpanel.setVisible(false);
        	mEdit.setEnabled(true);
        	mDel.setEnabled(true);
        }
		public void menuSelected(MenuItem selectedItem) {
			if (selectedItem.getText().equals(dbHelp.getWords("Refresh"))){
				try {
					dbHelp.getCompContainer().refresh();
					dbHelp.getCompAccContainer().refresh();
					dbHelp.getOrgschemaContainer().refresh();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
       	 	} else if (selectedItem.getText().equals(dbHelp.getWords("New"))){
            	Cpanel.setCaption(dbHelp.getWords("AddingOrganization"));
            	enableCPanel();
            	try {
            		dbHelp.getCompContainer().rollback();
                } catch (Exception ignored) {
                	AEHelper.logException(ignored,"Before new comp rollback");
                }
            	try
            	{
            	  Object tempItemId = dbHelp.getCompContainer().addItem();
            	  if (tempItemId==null) 
            	  {
	                	compaccordion.getWindow().showNotification(dbHelp.getWords("ServerOverloaded"), Notification.TYPE_ERROR_MESSAGE);
	                	disableCPanel();
            	  }
            	  else{
            		  CompForm.setItemDataSource(dbHelp.getCompContainer().getItem(tempItemId));
            		  MainId=tempItemId;
            	  }
            	}
            	catch(Exception e)
            	{
            		AEHelper.logException(e,"New comp");
                	compaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), Notification.TYPE_ERROR_MESSAGE);
                	disableCPanel();
            	}
            }else if (selectedItem.getText().equals(dbHelp.getWords("Edit"))) {
            	Cpanel.setCaption(dbHelp.getWords("EditingOrganization"));
            	enableCPanel();
            	try {
            		dbHelp.getCompContainer().rollback();
                } catch (Exception ignored) {
                	ignored.printStackTrace();
                	AEHelper.logException(ignored,"Before comp edit rollback");
                }
            	try
            	{
            	 CompForm.setItemDataSource(dbHelp.getCompContainer().getItem(CompGrid.getValue()));
            	}
            	catch(Exception e)
            	{
            		disableCPanel();
            		AEHelper.logException(e,"Comp edit");
            	}
            }else if (selectedItem.getText().equals(dbHelp.getWords("Delete"))){
            	compaccordion.getWindow().addWindow(new confWindow(dbHelp.getWords("RecordDeleting"),
            			dbHelp.getWords("OrganizationWillBeRemoved"),
            			new confWindow.Callback() {
							
							private static final long serialVersionUID = 5053817083273511190L;

							@Override
							public void onDialogResult(boolean resultIsYes) {
								
								if (resultIsYes){
									try {
					            		dbHelp.getCompContainer().rollback();
					                } catch (Exception ignored) {
					                	AEHelper.logException(ignored,"Comp before removal rollback");
					                }
									Object ID = CompGrid.getValue();
	
									try {
										dbHelp.removeCompany(ID,false);
										//dbHelp.getCompContainer().removeItem(ID);
										//dbHelp.getCompContainer().commit();
					                } catch (Exception e) {
					                	AEHelper.logException(e,"Comp removal");
					                	compaccordion.getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
					                }
					                CompGrid.select(null);
								}
								
							}
						}
            		));
            };
        }
    };
    
    private Command menuDCommand = new Command() {
        /**
		 * 
		 */
		private static final long serialVersionUID = 1309726789652195092L;

		public void menuSelected(MenuItem selectedItem) {
        	
        	 try {
                  dbHelp.setCompanyId(CompGrid.getValue());
        	 }
        	 catch(Exception e)
        	 {
        		 AEHelper.logException(e, "comp acc menu selected");
             	 compaccordion.getWindow().showNotification(dbHelp.getWords("ServerError")+": "+ e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
                 return;
        	 }
        	 if (selectedItem.getText().equals(dbHelp.getWords("New"))){
            	CDpanel.setCaption(dbHelp.getWords("AddingUser"));
            	CDpanel.setVisible(true);
            	mdEdit.setEnabled(false);
            	mdDel.setEnabled(false);
            	editComAccId=null;
            	try {
            		dbHelp.getCompAccContainer().rollback();
                } catch (Exception ignored) {
                	AEHelper.logException(ignored,"Before new comp acc rollback");
                }
            	try
            	{
            	   Object tempItemId = dbHelp.getCompAccContainer().addItem();
            	   if (tempItemId==null)
            	   {
	                	compaccordion.getWindow().showNotification(dbHelp.getWords("ServerOverloaded"), Notification.TYPE_ERROR_MESSAGE);
	                	CDpanel.setVisible(false);
	                	mdEdit.setEnabled(true);
	                	mdDel.setEnabled(true);
            	   }
            	   else
            	   CompAccForm.setItemDataSource(dbHelp.getCompAccContainer().getItem(tempItemId));
            	}
            	catch(Exception e)
            	{
            		AEHelper.logException(e,"New comp acc");
                	compaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), Notification.TYPE_ERROR_MESSAGE);
                	CDpanel.setVisible(false);
                	mdEdit.setEnabled(true);
                	mdDel.setEnabled(true);
            	}
            	//CompAccForm.getItemDataSource().getItemProperty("company").setValue();
            	for (Object vals:DBCOLS){
            		CompAccForm.getItemDataSource().getItemProperty(vals).setValue(false);
            	}
            }else if (selectedItem.getText().equals(dbHelp.getWords("Edit"))) {
            	CDpanel.setCaption(dbHelp.getWords("EditingUser"));
            	mdAdd.setEnabled(false);
            	mdDel.setEnabled(false);
            	CDpanel.setVisible(true);
            	try {
            		dbHelp.getCompAccContainer().rollback();
                } catch (Exception ignored) {
                	AEHelper.logException(ignored,"Comp acc rollback");
                }
            	try 
            	{
            		editComAccId=CompAccGrid.getValue();
            		if (editComAccId==null) return;
            	  CompAccForm.setItemDataSource(dbHelp.getCompAccContainer().getItem(editComAccId));
            	}
            	catch(Exception e)
            	{
            		AEHelper.logException(e,"Comp Acc Edit:");
            	}
            }else if (selectedItem.getText().equals(dbHelp.getWords("Delete"))){
            	compaccordion.getWindow().addWindow(new confWindow(dbHelp.getWords("RecordDeleting"),
            			dbHelp.getWords("DeletingUserFromOrganization"),
            			new confWindow.Callback() {
							
							/**
							 * 
							 */
							private static final long serialVersionUID = 5952451279354615886L;

							@Override
							public void onDialogResult(boolean resultIsYes) {
								
								if (resultIsYes){
									try {
										dbHelp.getCompAccContainer().rollback();
					                } catch (Exception ignored) {
					                	AEHelper.logException(ignored,"Comp acc removal before rollback");
					                }
									//dbHelp.getCompContainer().removeItem(MainId);
									Object ID = CompAccGrid.getValue();
									//compaccordion.getWindow().showNotification(ID.toString(), ID.toString(), Notification.TYPE_ERROR_MESSAGE);
					                try {
										dbHelp.getCompAccContainer().removeItem(ID);
					                	dbHelp.getCompAccContainer().commit();
					                } catch(AEForeignKeyException aefor)
					                {
					                	try { dbHelp.getCompAccContainer().rollback();}catch(Exception ignored){}
					                	compaccordion.getWindow().showNotification(dbHelp.getWords("BeforeDeletingTheUserPleaseDeleteCorrespondingPosts"), Notification.TYPE_ERROR_MESSAGE);
					                }
					                catch (Exception e) {
					                	AEHelper.logException(e,"Item removal");
					                	compaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
					                }
					                CompAccGrid.select(null);
						          
								}
								
							}
						}
            		));
            };
        }
    };
	
	public CompanyForm(DatabaseHelper dbHelper){
		
		this.dbHelp = dbHelper;
		compaccordion = new Accordion();
		compaccordion.setImmediate(false);
		//compaccordion.setSizeFull();
		
		CmainLayout = new VerticalLayout();
		CmainLayout.setImmediate(false);
		CmainLayout.setMargin(false);
		CmainLayout.setSpacing(true);
		
		CmenuBar = new MenuBar();
		CmenuBar.setImmediate(false);
		mAdd = CmenuBar.addItem(dbHelp.getWords("New"), menuCommand);
		mEdit = CmenuBar.addItem(dbHelp.getWords("Edit"), menuCommand);
		mEdit.setEnabled(false);
		mDel = CmenuBar.addItem(dbHelp.getWords("Delete"), menuCommand);
		mDel.setEnabled(false);
		mRefresh = CmenuBar.addItem(dbHelp.getWords("Refresh"), menuCommand); 
		CmainLayout.addComponent(CmenuBar);
		
		ChLayout2 = new HorizontalLayout();
		ChLayout2.setImmediate(false);

		ChLayout2.setMargin(false);
		//ChLayout2.setSizeFull();
		ChLayout2.setSpacing(true);	
		// CompGrid
		try
		{			
			Container compContainer = dbHelp.getCompContainer();
			CompGrid = new Table(null,compContainer);
		    CompGrid.setImmediate(true);
		    CompGrid.setContainerDataSource(dbHelp.getCompContainer());
		    CompGrid.setVisibleColumns(new Object[]{"code","name","email","post"});		
		    CompGrid.setColumnHeaders(dbHelp.getTranslatedStrings(new String[]{"Code","Name_company","Email","Post_company"}));	
		    CompGrid.setColumnCollapsingAllowed(true);
		    CompGrid.setColumnReorderingAllowed(true);
		    CompGrid.setSelectable(true);
		    //CompGrid.setSizeFull();
		    CompGrid.setStyleName(Runo.TABLE_SMALL);
		    CompGrid.setWidth("100%");
		    ChLayout2.addComponent(CompGrid);
		}
		catch(Exception e)
		{
			AEHelper.logException(e,"Company Container");
		}
		Cpanel = new Panel();
		Cpanel.setCaption(dbHelp.getWords("AddingOrganization"));
		Cpanel.setVisible(false);
		Cpanel.setImmediate(false);
		
		CvLayout2 = new VerticalLayout();
		CvLayout2.setImmediate(false);
		CvLayout2.setMargin(true);
		CompForm = new Form();
		CompForm.setFormFieldFactory(new DefaultFieldFactory(){
			/**
			 * 
			 */
			private static final long serialVersionUID = 7359753568658330130L;

			@Override
			public Field createField(Item item, Object propertyId,
                    Component uiContext) {
	
				Field field = super.createField(item, propertyId, uiContext);
				field.setRequired(true);
				field.setWidth("243px");
				if (propertyId.equals("id")){ 
					field.setVisible(false);
					field.setRequired(false);
				}
                if (propertyId.equals("code")){
                	field.setCaption(dbHelp.getWords("Code"));
                }
                if (propertyId.equals("post")){
                	field.setCaption(dbHelp.getWords("Post_company"));
                }
                if (propertyId.equals("name")){
                	field.setCaption(dbHelp.getWords("Name_company"));
                }
                if (propertyId.equals("password")){
                	field.setCaption(dbHelp.getWords("Password"));
                }
				if (propertyId.equals("email")) {
                    /* Add a validator for email and make it required */
                    field.addValidator(new EmailValidator(
                    		dbHelp.getWords("EmailMustContainAmpersandAndFullDomainName")));
                    field.setCaption(dbHelp.getWords("Email"));
                }
				
				if (field instanceof TextField) {
                    ((TextField) field).setNullRepresentation("");
                }
				
				return field;

			}
		});

		ChLayout3 = new HorizontalLayout();
		ChLayout3.setImmediate(true);
		
		// bAply
		bAply = new Button();
		bAply.setCaption(dbHelp.getWords("Apply"));
		bAply.setImmediate(true);
		bAply.setTabIndex(5);
		ChLayout3.addComponent(bAply);		
		// bCancel
		bCancel = new Button();
		bCancel.setCaption(dbHelp.getWords("Cancel"));
		bCancel.setImmediate(true);
		ChLayout3.addComponent(bCancel);
		CompForm.setFooter(ChLayout3);		
		CvLayout2.addComponent(CompForm);		
		Cpanel.setContent(CvLayout2);
		ChLayout2.addComponent(Cpanel);
		//ChLayout2.setExpandRatio(CompGrid, 1.0f);
		ChLayout2.setSizeUndefined();
		CgridPanel = new Panel();
		CgridPanel.setContent(ChLayout2);
		CgridPanel.setScrollable(true);
		CmainLayout.addComponent(CgridPanel);
		//CmainLayout.addComponent(ChLayout2);
		compaccordion.addTab(CmainLayout, dbHelp.getWords("Organizations"));
		//DETAIL
		CDetailLayout = new VerticalLayout();
		CDetailLayout.setImmediate(true);
		CDetailLayout.setMargin(false);
		CDetailLayout.setSpacing(false);
		CDetailLayout.setWidth("100%");		
		CDmenuBar = new MenuBar();
		CDmenuBar.setImmediate(false);
		mdAdd = CDmenuBar.addItem(dbHelp.getWords("New"), menuDCommand);
		mdEdit = CDmenuBar.addItem(dbHelp.getWords("Edit"), menuDCommand);
		mdEdit.setEnabled(false);
		mdDel = CDmenuBar.addItem(dbHelp.getWords("Delete"), menuDCommand);
		mdDel.setEnabled(false);
		CDetailLayout.addComponent(CDmenuBar);
		
		CDhLayout2 = new HorizontalLayout();
		CDhLayout2.setImmediate(false);

		CDhLayout2.setMargin(false);
		CDhLayout2.setHeight("100%");
		CDhLayout2.setSpacing(true);	
		CompAccGrid = new Table(null);
		CompAccGrid.setWidth("650px");
		CompAccGrid.setImmediate(true);
		
		refreshDetailGrid();
		CDhLayout2.addComponent(CompAccGrid);
		
		CDpanel = new Panel();
		CDpanel.setCaption(dbHelp.getWords("AddingOrganization"));
		CDpanel.setVisible(false);
		CDpanel.setImmediate(true);
		
		CDvLayout2 = new VerticalLayout();
		CDvLayout2.setImmediate(false);
		CDvLayout2.setMargin(true);
		CompAccForm = new Form();
		CompAccForm.setFormFieldFactory(new DefaultFieldFactory(){
			/**
			 * 
			 */
			private static final long serialVersionUID = 8532317475780771407L;

			@Override
			public Field createField(Item item, Object propertyId,
                    Component uiContext) {
				Field field = super.createField(item, propertyId, uiContext);
				field.setWidth("243px");
				if (propertyId.equals("email")|| propertyId.equals("nik")|| propertyId.equals("name")){
					field.setRequired(true);
				}
				if (field instanceof TextField) {
                    ((TextField) field).setNullRepresentation("");
                }
				/*if (field instanceof CheckBox) {
                    ((CheckBox) field).setValue(true);
                }*/

				if (propertyId.equals("id")){ 
					field.setVisible(false);
				} else
				if (!propertyId.equals("company")){
				field.setCaption(dbHelp.getWords(DCAPT[Arrays.asList(DCOLS).indexOf(propertyId.toString())]));
				} else {
					field.setVisible(false);
				}
				if (propertyId.equals("email")) {
                    /* Add a validator for email and make it required */
                    field.addValidator(new EmailValidator(
                    		dbHelp.getWords("EmailMustContainAmpersandAndFullDomainName")
                            ));
                }				
				return field;

			}
		});
		CDhLayout3 = new HorizontalLayout();
		CDhLayout3.setImmediate(false);
		
		// bAply
		bDAply = new Button();
		bDAply.setCaption(dbHelp.getWords("Apply"));
		bDAply.setImmediate(true);
		bDAply.setTabIndex(5);
		CDhLayout3.addComponent(bDAply);
		
		// bCancel
		bDCancel = new Button();
		bDCancel.setCaption(dbHelp.getWords("Cancel"));
		bDCancel.setImmediate(true);
		CDhLayout3.addComponent(bDCancel);
		//addButtonListeners();
		CompAccForm.setFooter(CDhLayout3);		
		CDvLayout2.addComponent(CompAccForm);
		CDpanel.setContent(CDvLayout2);
		CDhLayout2.addComponent(CDpanel);
		CDgridPanel = new Panel();
		CDgridPanel.setContent(CDhLayout2);
		CDgridPanel.setScrollable(true);
		CDetailLayout.addComponent(CDgridPanel);
		CDetailLayout.setVisible(false);
		compaccordion.addTab(CDetailLayout,dbHelp.getWords("AssignedUsers"));
		compaccordion.addListener(new TabSheet.SelectedTabChangeListener() {
			
			private static final long serialVersionUID = 1L;

			@Override
			public void selectedTabChange(SelectedTabChangeEvent event) {
				
				int pos = compaccordion.getTabPosition(compaccordion.getTab(compaccordion.getSelectedTab()));
				String pagename=null;
				switch(pos)
				{
				case 0:
					pagename="companies";
					break;
				case 1:
					pagename="companies.compacc";
					break;
				}
				if (pagename!=null) try
						{
					       dbHelp.getCurrentUserTrackItem().getItemProperty("last_page").setValue(pagename);
					       dbHelp.saveCurrentUserTrackInfo();
						}
				       catch(Exception e)
				       {
				    	   e.printStackTrace();
				       }		
								
			}
		});
		addButtonListeners();
		addGridListeners();
	}
	
	private void addGridListeners(){
		CompGrid.addListener(new Property.ValueChangeListener() {

			 
			private static final long serialVersionUID = 3520836255628012161L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				Property property = event.getProperty();
		        if (property == CompGrid) {
		            Item item = CompGrid.getItem(CompGrid.getValue());
		            if (item != CompForm.getItemDataSource()) {
		            	if (CompGrid.getValue()==null){
		            		mEdit.setEnabled(false);
		            		mDel.setEnabled(false);
		            		CDetailLayout.setVisible(false);
		            	} else {
		            		mEdit.setEnabled(true);
		            		mDel.setEnabled(true);
		            		CDetailLayout.setVisible(true);
		            	}
		            	mAdd.setEnabled(true);
		            	Cpanel.setVisible(false);
		            	refreshDetailGrid();
		            }
		        }
				
			}
		} );
		CompAccGrid.addListener(new Property.ValueChangeListener() {
			
			/**
			 * 
			 */
			private static final long serialVersionUID = -4262942439248536230L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				Property property = event.getProperty();
		        if (property == CompAccGrid) {
		            Item item = CompAccGrid.getItem(CompAccGrid.getValue());
		            if (item != CompAccForm.getItemDataSource()) {
		            	if (CompAccGrid.getValue()==null){
		            		mdEdit.setEnabled(false);
		            		mdDel.setEnabled(false);
		            	} else {
		            		mdEdit.setEnabled(true);
		            		mdDel.setEnabled(true);
		            	}
		            	//mEdit.setEnabled(!mEdit.isEnabled());
		            	//mDel.setEnabled(!mDel.isEnabled());
		            	mdAdd.setEnabled(true);
		            	CDpanel.setVisible(false);           	
		            }
		        }
				
			}
		} );
	}	
	private void addButtonListeners(){
		bAply.addListener(new Button.ClickListener() {			
			/**
			 * 
			 */
			private static final long serialVersionUID = -3143253462555220935L;

			@Override
			public void buttonClick(ClickEvent event) {
				CompForm.commit();
				if (!CompForm.isValid()) {
	                return;
	            }
				try {
					
					dbHelp.setCompanyId(MainId);
					Object orgItemId = dbHelp.getOrgschemaContainer().addItem();
					if (orgItemId==null){}					
					dbHelp.getOrgschemaContainer().setPropertiesOfItem(orgItemId, "pid", 0);
					dbHelp.getOrgschemaContainer().setPropertiesOfItem(orgItemId, "level", 0);
					dbHelp.getOrgschemaContainer().setPropertiesOfItem(orgItemId, "docs", "");
					dbHelp.getOrgschemaContainer().setPropertiesOfItem(orgItemId, "manager", true);
					dbHelp.getOrgschemaContainer().setPropertiesOfItem(orgItemId, "code", 
							dbHelp.getCompContainer().getContainerProperty(MainId, "code").getValue());
					dbHelp.getOrgschemaContainer().setPropertiesOfItem(orgItemId, "name", 
							dbHelp.getCompContainer().getContainerProperty(MainId, "post").getValue());
					String deptname=(String)dbHelp.getCompContainer().getContainerProperty(MainId, "name").getValue();
					System.out.println("deptname:"+deptname);
					dbHelp.getOrgschemaContainer().setPropertiesOfItem(orgItemId, "dept_name",
							deptname);
					//dbHelp.getOrgschemaContainer().setCommitDependant(dbHelp.getCompContainer());
					dbHelp.getCompContainer().commit();
					dbHelp.getOrgschemaContainer().commit();
		            
		        } catch (Exception e) {
		        	AEHelper.logException(e,"Apply button click");
		        	compaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
		        }
				Cpanel.setVisible(false);
				
			}
		});
		bCancel.addListener(new Button.ClickListener() {			
			/**
			 * 
			 */
			private static final long serialVersionUID = -6839497274631461435L;

			@Override
			public void buttonClick(ClickEvent event) {
				try {
					dbHelp.getCompContainer().rollback();
		        } catch (Exception e) {
		        	AEHelper.logException(e,"Cancel button");
		        	compaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
		        }
				CompForm.setItemDataSource(null);
				Cpanel.setVisible(false);
			}
		});
		bDAply.addListener(new Button.ClickListener() {			
			/**
			 * 
			 */
			private static final long serialVersionUID = -8375927111394468178L;

			@Override
			public void buttonClick(ClickEvent event) {
				CompAccForm.commit();
				if (!CompAccForm.isValid()) {
	                return;
	            }
				try {
					dbHelp.getCompAccContainer().commit();
					if (editComAccId!=null) 
						{
						    dbHelp.views.docservice.notifyOfCompAccChange(editComAccId);
						}
		        } catch (Exception e) {
		        	AEHelper.logException(e,"Comp acc Ok button click");
		        	compaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
		        }
				CDpanel.setVisible(false);
				
			}
		});
		bDCancel.addListener(new Button.ClickListener() {			
			/**
			 * 
			 */
			private static final long serialVersionUID = -4491778313902174492L;

			@Override
			public void buttonClick(ClickEvent event) {
				try {
					dbHelp.getCompAccContainer().rollback();
		        } catch (Exception e) {
		        	AEHelper.logException(e,"Comp Acc DCancel Button");
		        	compaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
		        }
				CompAccForm.setItemDataSource(null);
				CDpanel.setVisible(false);
			}
		});
	}
	public void setCompAccEntryPoint()
	{
		Integer comp=dbHelp.getCompanyId();
		if (comp==null) return;
		CompGrid.setValue(comp);
		refreshDetailGrid();
		if (MainId!=null && !MainId.equals(new Integer(0)))
		{
			compaccordion.setSelectedTab(CDetailLayout);
		}
	}
	public void refreshDetailGrid(){
		if (CompGrid.getValue()==null) {
    		MainId = 0;
    	} else {
    		MainId =Integer.parseInt(CompGrid.getValue().toString());
    	}
		try
		{
			dbHelp.setCompanyId(MainId);
		    CompAccGrid.setContainerDataSource(dbHelp.getCompAccContainer());
		}
		catch(Exception e)
		{
			AEHelper.logException(e,"refresh detailed grid");
		}
		//for(Object Column:DBCOLS){
			/*CompAccGrid.addGeneratedColumn("isstatadmin", new ColumnGenerator(){

				public Component generateCell(Table source, Object itemId,
	                    Object columnId) {
	                if (CompAccGrid.getItem(itemId).getItemProperty("isstatadmin").getValue() != null) {
	                	Label l = new Label();
	                    if (CompAccGrid.getItem(itemId).getItemProperty("isstatadmin").getValue()=="false"){
	                    	l.setValue("Нет");
	                    } else {
	                    	l.setValue("Да");
	                    }
	                    l.setSizeUndefined();
	                    return l;
	                }
	                return null;
	            }
			});*/
		//}
		CompAccGrid.setVisibleColumns(DCOLS);		
		CompAccGrid.setColumnHeaders(dbHelp.getTranslatedStrings(DCAPT));
		
		CompAccGrid.setColumnCollapsingAllowed(true);
		CompAccGrid.setColumnReorderingAllowed(true);
		CompAccGrid.setSelectable(true);
		//CompAccGrid.setSizeFull();
		CompAccGrid.setStyleName(Runo.TABLE_SMALL);
		CompAccGrid.setHeight("100%");
	}
	
	public Accordion getCompanyForm(){
		return compaccordion;
	}
	

}
